<template>
	<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" width="90" height="90"
	:disabled="fileListData.length>0?true:false" multiple :ifShowUpload="ifShowUpload&&Ifslots">
		<view class="uploadBox" v-if="fileList.length==0">
			<view class="photograph">
				<u-icon name="camera" size="50" color="#f40"></u-icon>
			</view>
			<view class="title">上传小票以及消费凭证照片（必填）</view>
		</view>
	</u-upload>
</template>

<script>
	export default {
		name:"upload-file",
		props:{
			fileListData:{
				type:Array,
				default(){
					return []
				}
			},
			Ifslots:{//是否自定义样式，没有图片，有图片则隐藏
				type:Boolean,
				default:false,
			},
			implementType:{//空代表可以上传图片 不为空则是详情，不能上传
				type:String,
				default:''
			}
		},
		data() {
			return {
				fileList:[],
				ifShowUpload:false,
			};
		},
		mounted() {
			this.fileList=[...this.fileListData]//详情渲染
		},
		methods:{
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
			},
			afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let that=this
				let errorNum=0
				let successNum=0
				let chooseImageList=[]
				event.file.forEach(function(item){
					if(item.size> 1024*1024 *9){//限制图片大小
						errorNum+=1
					}else{
						successNum+=1
						chooseImageList.push(item.url)
					}
				})
				if(successNum>0){//限制图片大小方法通过
				    uni.showLoading({
				     	title: '图片压缩中...'
				    })
					chooseImageList.forEach(function(item,index){
						if(item.slice(-3)=='jpg'){
							uni.compressImage({
								src: item,
								quality: 20,
								success: function(compress) { 
									that.fileList.push({url:compress.tempFilePath})
								},
							})
						}else{
							that.fileList.push({url:item})
						}
						if(successNum==index+1){
							uni.hideLoading()
						}
					})
				}else if(errorNum>0&&successNum==0){//限制图片大小方法不通过
					uni.$u.toast(`上传失败，图片大小都超过9M，请重新选择！`)
					return
				}else if(errorNum>0&&successNum>0){
					uni.$u.toast(`有${errorNum}张图片大小都超过9M，无法上传`)
				}
				
				if(that.fileList){
					that.ifShowUpload=true
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
// 上传图片框
.uploadBox{
	margin:20px 0;
	background:#fff;
	box-shadow: 0px 1px 8px 1px rgba(167, 167, 167, 0.2 );
	height:160px;
	display: flex;
	justify-content: center;
	align-items: center;
	flex-direction: column;
	.photograph{
		height:80px;
		width:80px;
		background:#f9f9f9;
		border-radius:50%;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.title{
		font-size:14px;
		margin-top:15px;
	}
}
</style>